import Vue from 'vue'
import VueResource from 'vue-resource'
import VueRouter from 'vue-router'
import Gxt from './components/Gxt.vue'
import 'vux/dist/vux.css'
import Echarts from 'echarts/lib/echarts.js'

/* 部署一个新版本主要修改参数：Env, ENTERPRISE */

window.Echarts = Echarts  // 引入echarts
var USERNAME = '' // 用户名
var DefaultPage = '/index' // 用户首次进入的页面，index为大行业选择，home为首页
var Env = 'pro' // pro 为生产环境 test为测试环境 dev 开发环境
var datasource = '' // 数据源
var DOMAIN = 'https://mapnew.midea.com/mas-api/restful/mdgxt' // 默认为生产环境的地址
var accessToken = ''  // 接口访问token
var ENTERPRISE = 'MIDEA' // 企业代号，默认为美的-MIDEA，奥飞-ALPHA，全部行业-ALL
var datasourceList = [] // 用户行业权限列表

// 接口地址
if (Env === 'pro') {
  DOMAIN = 'https://mapnew.midea.com/mas-api/restful/mdgxt'
} else if (Env === 'test') {
  DOMAIN = 'https://newimtest.midea.com/mas-api/restful/mdgxt'
} else {
  DOMAIN = 'api'
}

// 安装 vue resource 插件
Vue.use(VueResource)
// vue resource 设置解释json
Vue.http.options.emulateJSON = true
// 求情超时
Vue.http.interceptors.push((request, next) => {
  var timeout
  if (request._timeout) {
    timeout = setTimeout(() => {
      next(request.respondWith(request.body, {
        status: 408,
        statusText: 'Request Timeout'
      }))
    }, request._timeout)
  }

  next((response) => {
    clearTimeout(timeout)
  })
})

/* 等待底座环境加载，检测用户是否登陆 */
var app = {
  // Application Constructor
  initialize: function () {
    document.addEventListener('deviceready', this.onDeviceReady.bind(this), false)
  },
  onDeviceReady: function () {
    if (window.cordova) {
      // 下面的底座方法只有ios有
      if (util.getDevInfo() === 1) {
        // ios禁止过渡滑动，0禁止，1开启
        window.cordova.exec(function (success) {
        }, function (error) {
          console.log('Error: ' + error)
        }, 'MideaCommon', 'setBounces', [0])

        // 设置状态栏颜色
        window.cordova.exec(function (success) {
          // window.alert(success)
        }, function (error) {
          console.log('Error: ' + error)
        }, 'MideaCommon', 'statusBarColor', [255, 255, 255, 1])
      }
      // 从底座获取用户名和token
      window.cordova.exec(function (success) {
        // 用户名
        USERNAME = success.uid
        // 访问token
        accessToken = success.ssoToken
        // 获取权限列表
        getAuthorizeList(function () {
          // 初始化全局变量
          setGlobalEvn()
          // 初始化行业数据源
          window.getDatasource()
          initApp()
        })
        /* 定时重新从底座获取successToken */
        setInterval(function () {
          if (window.cordova) {
            window.cordova.exec(function (success) {
              accessToken = success.ssoToken
              window.getDatasource()
            }, function (error) {
              window.alert('获取用户失败: ' + error.toString())
            }, 'MideaUser', 'getUser', [])
          }
        }, 5400000)
      }, function (error) {
        window.alert('获取用户失败: ' + error.toString())
      }, 'MideaUser', 'getUser', [])
    }
  }
}

/* 获取用户权限列表 */
function getAuthorizeList (callback) {
  try {
    // 欢迎页权限接口
    var limits = DOMAIN + '/getUserDepart' + '?username=' + USERNAME + '&accessToken=' + accessToken + '&enterprise=' + ENTERPRISE
    Vue.http.post(limits, {_timeout: 10000}).then((res) => {
      datasourceList = res.json().data
      window.sessionStorage.datasourceList = JSON.stringify(datasourceList)
      if (typeof callback === 'function') {
        callback()
      }
    }, (res) => {
      window.alert('权限接口请求失败，请检查网络重试！')
    })
  } catch (error) {
    window.alert('初始化应用失败，请退出重试！')
  }
}

/* 设置全局的变量环境 */
/* 设置全局的变量环境 */
function setGlobalEvn () {
  if (Array.isArray(datasourceList) && datasourceList.length > 1) {
    DefaultPage = '/index'
  } else {
    DefaultPage = '/home'
    window.localStorage.datasource = datasource = Array.isArray(datasourceList) ? datasourceList[0] || 'jiadian' : 'jiadian'
  }
}

// 接口信息，datasource参数需要在点击进入大行业时获取
window.getDatasource = function () {
  datasource = window.localStorage.datasource
  window.interface = {
    // 登陆和退出接口
    oauth: {
      login: DOMAIN + '/login',
      logout: DOMAIN + '/logout'
    },
    // 欢迎页权限接口
    limits: DOMAIN + '/getUserDepart' + '?username=' + USERNAME + '&accessToken=' + accessToken + '&enterprise=' + ENTERPRISE,
    // 首页--产品
    productMonitor: {
      // 品牌热度
      brandHot: DOMAIN + '/chart/datas' + '?datasource=' + datasource + '&username=' + USERNAME + '&accessToken=' + accessToken + '&enterprise=' + ENTERPRISE,
      // 热销产品
      topSale: DOMAIN + '/productMonitor/topSale' + '?datasource=' + datasource + '&username=' + USERNAME + '&accessToken=' + accessToken + '&enterprise=' + ENTERPRISE,
      //  新品上市
      newLauchProduct: DOMAIN + '/productMonitor/newLauchProduct' + '?datasource=' + datasource + '&username=' + USERNAME + '&accessToken=' + accessToken + '&enterprise=' + ENTERPRISE,
      // 对比列表页
      comparision: DOMAIN + '/productMonitor/comparision' + '?datasource=' + datasource + '&username=' + USERNAME + '&accessToken=' + accessToken + '&enterprise=' + ENTERPRISE,
      // 增加产品至对比列表
      add: DOMAIN + '/productMonitor/comparision/add' + '?datasource=' + datasource + '&username=' + USERNAME + '&accessToken=' + accessToken + '&enterprise=' + ENTERPRISE,
      // 从对比列表中删除产品
      delete: DOMAIN + '/productMonitor/comparision/delete' + '?datasource=' + datasource + '&username=' + USERNAME + '&accessToken=' + accessToken + '&enterprise=' + ENTERPRISE
    },
    //  筛选列表筛选条件
    conditions: DOMAIN + '/conditions' + '?datasource=' + datasource + '&username=' + USERNAME + '&accessToken=' + accessToken + '&enterprise=' + ENTERPRISE,
    //  筛选列表品牌
    brands: DOMAIN + '/loadBrands' + '?datasource=' + datasource + '&username=' + USERNAME + '&includeCollect=true' + '&accessToken=' + accessToken + '&enterprise=' + ENTERPRISE,
    //  知己彼首页（列表页）
    peerNav: DOMAIN + '/nav' + '?datasource=' + datasource + '&username=' + USERNAME + '&moduleId=2' + '&accessToken=' + accessToken + '&enterprise=' + ENTERPRISE,
    //  知己彼各页面数据
    peerData: DOMAIN + '/chart/datas' + '?datasource=' + datasource + '&username=' + USERNAME + '&accessToken=' + accessToken + '&enterprise=' + ENTERPRISE,
    // 掌大局导航页接口数据
    indusNav: DOMAIN + '/nav' + '?datasource=' + datasource + '&username=' + USERNAME + '&moduleId=1' + '&accessToken=' + accessToken + '&enterprise=' + ENTERPRISE,
    // 掌大局页面接口数据
    indusPage: DOMAIN + '/chart/datas' + '?datasource=' + datasource + '&username=' + USERNAME + '&accessToken=' + accessToken + '&enterprise=' + ENTERPRISE,
    // 产品体验品牌对比三级筛选条件接口数据
    experienceBrandFilter: DOMAIN + '/api/koubei/propertys?datasource=' + datasource + '&username=' + USERNAME + '&accessToken=' + accessToken + '&enterprise=' + ENTERPRISE,
    // 选择产品弹窗
    loadProducts: DOMAIN + '/loadProducts?datasource=' + datasource + '&username=' + USERNAME + '&accessToken=' + accessToken + '&enterprise=' + ENTERPRISE,
    // 我的关注
    collBrand: DOMAIN + '/loadBrands?datasource=' + datasource + '&username=' + USERNAME + '&accessToken=' + accessToken + '&enterprise=' + ENTERPRISE,
    // 添加品牌到我的关注
    addCollBrand: DOMAIN + '/user/collBrand/add?datasource=' + datasource + '&username=' + USERNAME + '&accessToken=' + accessToken + '&enterprise=' + ENTERPRISE,
    // 移除我的关注
    delCollBrand: DOMAIN + '/user/collBrand/delete?datasource=' + datasource + '&username=' + USERNAME + '&accessToken=' + accessToken + '&enterprise=' + ENTERPRISE
  }
}

/* 检测到用户合法后加载内容 */
function initApp () {
  // 安装 vue 路由
  Vue.use(VueRouter)
  // vue debug 信息
  Vue.config.debug = Env !== 'pro'

  var Router = new VueRouter({})

  // 格式化时间  2016-11-21 ==> 20161121
  Vue.filter('formatDate', function (val) {
    if (val) {
      return val.replace(/-/g, '')
    } else {
      return ''
    }
  })

  // 路由配置
  Router.map({
    // 欢迎页
    '/index': {
      name: '/index',
      component: function (resolve) {
        require(['./components/index.vue'], resolve)
      }
    },
    // 大行业主页
    '/home': {
      name: '/home',
      component: function (resolve) {
        require(['./components/home/Home.vue'], resolve)
      }
    },
    // 掌大局导航页
    '/industry/industryHome': {
      name: '/industry/industryHome',
      component: function (resolve) {
        require(['./components/industry/industryHome.vue'], resolve)
      }
    },
    // 行业汇总分析_行业总体概览 industryOviews
    '/industry/industryOviews': {
      name: '/industry/industryOviews',
      component: function (resolve) {
        require(['./components/industry/compass/industryOviews.vue'], resolve)
      },
      meta: {
        page: 'industryOviews'
      }
    },
    // 行业汇总分析_各品类销售情况	theSales
    '/industry/theSales': {
      name: '/industry/theSales',
      component: function (resolve) {
        require(['./components/industry/compass/theSales.vue'], resolve)
      },
      meta: {
        page: 'theSales'
      }
    },
    // 行业汇总分析_行业明星产品	starProduct
    '/industry/starProduct': {
      name: '/industry/starProduct',
      component: function (resolve) {
        require(['./components/industry/compass/starProduct.vue'], resolve)
      },
      meta: {
        page: 'starProduct'
      }
    },
    // 行业汇总分析_总体店铺排行	storeRanking
    '/industry/storeRanking': {
      name: '/industry/storeRanking',
      component: function (resolve) {
        require(['./components/industry/compass/storeRanking.vue'], resolve)
      },
      meta: {
        page: 'storeRanking'
      }
    },
    // 行业汇总分析_单品牌数据概览	singleDataOviews
    '/industry/singleDataOviews': {
      name: '/industry/singleDataOviews',
      component: function (resolve) {
        require(['./components/industry/compass/singleDataOviews.vue'], resolve)
      },
      meta: {
        page: 'singleDataOviews'
      }
    },
    // 行业汇总分析_单品牌各品类销售	singleCategorySales
    '/industry/singleCategorySales': {
      name: '/industry/singleCategorySales',
      component: function (resolve) {
        require(['./components/industry/compass/singleCategorySales.vue'], resolve)
      },
      meta: {
        page: 'singleCategorySales'
      }
    },
    // 行业汇总分析_单品牌各品类评价	singleCategoryEvaluation
    '/industry/singleCategoryEvaluation': {
      name: '/industry/singleCategoryEvaluation',
      component: function (resolve) {
        require(['./components/industry/compass/singleCategoryEvaluation.vue'], resolve)
      },
      meta: {
        page: 'singleCategoryEvaluation'
      }
    },
    // 品类竞争分析_品牌数据概览	dataOviews
    '/industry/dataOviews': {
      name: '/industry/dataOviews',
      component: function (resolve) {
        require(['./components/industry/compass/dataOviews.vue'], resolve)
      },
      meta: {
        page: 'dataOviews'
      }
    },
    // 品类竞争分析_行业价格分析	priceAnalysis
    '/industry/priceAnalysis': {
      name: '/industry/priceAnalysis',
      component: function (resolve) {
        require(['./components/industry/compass/priceAnalysis.vue'], resolve)
      },
      meta: {
        page: 'priceAnalysis'
      }
    },
    // 品类竞争分析_品牌销售竞争	marketingCompetition
    '/industry/marketingCompetition': {
      name: '/industry/marketingCompetition',
      component: function (resolve) {
        require(['./components/industry/compass/marketingCompetition.vue'], resolve)
      },
      meta: {
        page: 'marketingCompetition'
      }
    },
    // 品类竞争分析_品牌评价竞争	priceCompetition
    '/industry/priceCompetition': {
      name: '/industry/priceCompetition',
      component: function (resolve) {
        require(['./components/industry/compass/priceCompetition.vue'], resolve)
      },
      meta: {
        page: 'priceCompetition'
      }
    },
    // 品类竞争分析_产品竞争分析	competitionAnalysis
    '/industry/competitionAnalysis': {
      name: '/industry/competitionAnalysis',
      component: function (resolve) {
        require(['./components/industry/compass/competitionAnalysis.vue'], resolve)
      },
      meta: {
        page: 'competitionAnalysis'
      }
    },
    // 品类口碑分析_行业口碑分析	praiseAnalysis
    '/industry/praiseAnalysis': {
      name: '/industry/praiseAnalysis',
      component: function (resolve) {
        require(['./components/industry/compass/praiseAnalysis.vue'], resolve)
      },
      meta: {
        page: 'praiseAnalysis'
      }
    },
    // 品牌市场表现 	performance
    '/industry/performance': {
      name: '/industry/performance',
      component: function (resolve) {
        require(['./components/industry/compass/performance.vue'], resolve)
      },
      meta: {
        page: 'performance'
      }
    },
    // 畅销产品分析	  bestSelling
    '/industry/bestSelling': {
      name: '/industry/bestSelling',
      component: function (resolve) {
        require(['./components/industry/compass/bestSelling.vue'], resolve)
      },
      meta: {
        page: 'bestSelling'
      }
    },
    // 品牌关注点分析 	brandFocus
    '/industry/brandFocus': {
      name: '/industry/brandFocus',
      component: function (resolve) {
        require(['./components/industry/compass/brandFocus.vue'], resolve)
      },
      meta: {
        page: 'brandFocus'
      }
    },
    // 品牌整体评价	 holisticAnalysis
    '/industry/holisticAnalysis': {
      name: '/industry/holisticAnalysis',
      component: function (resolve) {
        require(['./components/industry/compass/holisticAnalysis.vue'], resolve)
      },
      meta: {
        page: 'holisticAnalysis'
      }
    },
    // 品牌深度评价	 depthAnalysis
    '/industry/depthAnalysis': {
      name: '/industry/depthAnalysis',
      component: function (resolve) {
        require(['./components/industry/compass/depthAnalysis.vue'], resolve)
      },
      meta: {
        page: 'depthAnalysis'
      }
    },
    // 产品基本信息 	productInfo
    '/industry/productInfo': {
      name: '/industry/productInfo',
      component: function (resolve) {
        require(['./components/industry/compass/productInfo.vue'], resolve)
      },
      meta: {
        page: 'productInfo'
      }
    },
    // 产品销售趋势 	productSalesTrends
    '/industry/productSalesTrends': {
      name: '/industry/productSalesTrends',
      component: function (resolve) {
        require(['./components/industry/compass/productSalesTrends.vue'], resolve)
      },
      meta: {
        page: 'productSalesTrends'
      }
    },
    // 产品平台和店铺分布	 productDistribution
    '/industry/productDistribution': {
      name: '/industry/productDistribution',
      component: function (resolve) {
        require(['./components/industry/compass/productDistribution.vue'], resolve)
      },
      meta: {
        page: 'productDistribution'
      }
    },
    // 产品整体评价分析	 evaluationAnalysis
    '/industry/evaluationAnalysis': {
      name: '/industry/evaluationAnalysis',
      component: function (resolve) {
        require(['./components/industry/compass/evaluationAnalysis.vue'], resolve)
      },
      meta: {
        page: 'evaluationAnalysis'
      }
    },
    // 产品评价深度分析 	f
    '/industry/evaluationMoreAnalysis': {
      name: '/industry/evaluationMoreAnalysis',
      component: function (resolve) {
        require(['./components/industry/compass/evaluationMoreAnalysis.vue'], resolve)
      },
      meta: {
        page: 'evaluationMoreAnalysis'
      }
    },
    // 产品体验指标对比 	experienceIndex
    '/industry/experienceIndex': {
      name: '/industry/experienceIndex',
      component: function (resolve) {
        require(['./components/industry/compass/experienceIndex.vue'], resolve)
      },
      meta: {
        page: 'experienceIndex'
      }
    },
    // 产品体验品牌对比	 experienceBrand
    '/industry/experienceBrand': {
      name: '/industry/experienceBrand',
      component: function (resolve) {
        require(['./components/industry/compass/experienceBrand.vue'], resolve)
      },
      meta: {
        page: 'experienceBrand'
      }
    },
    // 产品体验型号排行	 experiencemodel
    '/industry/experiencemodel': {
      name: '/industry/experiencemodel',
      component: function (resolve) {
        require(['./components/industry/compass/experiencemodel.vue'], resolve)
      },
      meta: {
        page: 'experiencemodel'
      }
    },
    // 天猫店铺跳转
    '/industry/tianmaoStore': {
      name: '/industry/tianmaoStore',
      component: function (resolve) {
        require(['./components/industry/compass/tianmaoStore.vue'], resolve)
      }
    },
    // 知己比
    '/peer': {
      name: '/peer/listAll',
      component: function (resolve) {
        require(['./components/peer/listAll.vue'], resolve)
      }
    },
    // 品牌整体对标
    '/peer/brandOverallComparison': {
      name: '/peer/brandOverallComparison',
      component: function (resolve) {
        require(['./components/peer/brand/brandOverallComparison.vue'], resolve)
      },
      meta: {
        page: 'brandOverallComparison'
      }
    },
    // 品牌销售对比
    '/peer/brandSalesComparison': {
      name: '/peer/brandSalesComparison',
      component: function (resolve) {
        require(['./components/peer/brand/brandSalesComparison.vue'], resolve)
      },
      meta: {
        page: 'brandSalesComparison'
      }
    },
    // 品牌评价整体对比
    '/peer/brandOverallEvaluation': {
      name: '/peer/brand/brandOverallEvaluation',
      component: function (resolve) {
        require(['./components/peer/brand/brandOverallEvaluation.vue'], resolve)
      },
      meta: {
        page: 'brandOverallEvaluation'
      }
    },
    // 品牌评价详细对比
    '/peer/brandDetailedEvaluation': {
      name: '/peer/brandDetailedEvaluation',
      component: function (resolve) {
        require(['./components/peer/brand/brandDetailedEvaluation.vue'], resolve)
      },
      meta: {
        page: 'brandDetailedEvaluation'
      }
    },
    // 产品整体对标
    '/peer/productOverallComparison': {
      name: '/peer/productOverallComparison',
      component: function (resolve) {
        require(['./components/peer/product/productOverallComparison.vue'], resolve)
      },
      meta: {
        page: 'productOverallComparison'
      }
    },
    // 产品销售对比
    '/peer/productSalesComparison': {
      name: '/peer/productSalesComparison',
      component: function (resolve) {
        require(['./components/peer/product/productSalesComparison.vue'], resolve)
      },
      meta: {
        page: 'productSalesComparison'
      }
    },
    // 产品评价整体对比
    '/peer/productOverallEvaluation': {
      name: '/peer/productOverallEvaluation',
      component: function (resolve) {
        require(['./components/peer/product/productOverallEvaluation.vue'], resolve)
      },
      meta: {
        page: 'productOverallEvaluation'
      }
    },
    // 产品评价详细对比
    '/peer/productDetailedEvaluation': {
      name: '/peer/productDetailedEvaluation',
      component: function (resolve) {
        require(['./components/peer/product/productDetailedEvaluation.vue'], resolve)
      },
      meta: {
        page: 'productDetailedEvaluation'
      }
    },
    '/peer/contrast': {
      name: '/peer/contrast',
      component: function (resolve) {
        require(['./components/peer/Contrast.vue'], resolve)
      }
    },
    '/account': {
      name: '/account',
      component: function (resolve) {
        require(['./components/account/Account.vue'], resolve)
      }
    },
    '/account/accountIntroduce/overview': {
      name: '/account/accountIntroduce/overview',
      component: function (resolve) {
        require(['./components/account/OverView.vue'], resolve)
      }
    },
    '/account/accountIntroduce/core': {
      name: '/account/accountIntroduce/core',
      component: function (resolve) {
        require(['./components/account/Core.vue'], resolve)
      }
    },
    '/account/accountIntroduce/function': {
      name: '/account/accountIntroduce/function',
      component: function (resolve) {
        require(['./components/account/Function.vue'], resolve)
      }
    },
    '/account/accountIntroduce/successfulcase': {
      name: '/account/accountIntroduce/successfulcase',
      component: function (resolve) {
        require(['./components/account/SuccessfulCase.vue'], resolve)
      }
    },
    '/account/accountIntroduce/moreproduct': {
      name: '/account/accountIntroduce/moreproduct',
      component: function (resolve) {
        require(['./components/account/MoreProduct.vue'], resolve)
      }
    },
    '/account/myconcern': {
      name: '/account/myConcern',
      component: function (resolve) {
        require(['./components/account/MyConcernNew.vue'], resolve)
      },
      meta: {
        page: 'myCollect'
      }
    },
    '/account/accountIntroduce/explain': {
      name: '/account/accountIntroduce/explain',
      component: function (resolve) {
        require(['./components/account/Explain.vue'], resolve)
      }
    },
    '/brand': {
      name: '/home/brand',
      component: function (resolve) {
        require(['./components/home/Brand.vue'], resolve)
      },
      meta: {
        page: 'brandMonitor'
      }
    },
    '/store': {
      name: '/home/store',
      component: function (resolve) {
        require(['./components/home/Store.vue'], resolve)
      },
      meta: {
        page: 'storeMonitor'
      }
    },
    '/product': {
      name: '/home/product',
      component: function (resolve) {
        require(['./components/home/Product.vue'], resolve)
      },
      meta: {
        page: 'productMonitor'
      }
    },
    '/user': {
      name: '/home/user',
      component: function (resolve) {
        require(['./components/home/User.vue'], resolve)
      }
    }
  })

  Router.redirect({
    '*': DefaultPage
  })

  Router.start(Gxt, '#app')

  // 统计每个页面访问记录
  Router.beforeEach(function (transition) {
    var meta = transition.to.matched[0].handler.meta
    try {
      if (meta && meta.page) {
        var currPage = meta.page
        var pageVisitInterface = DOMAIN + '/pageVisit' + '?page=' + currPage + '&username=' + USERNAME + '&enterprise=' + ENTERPRISE
        console.log(currPage, pageVisitInterface)
        // 将页面访问记录发送给后台
        Vue.http.get(pageVisitInterface, {_timeout: 10000})
      }
    } finally {
      transition.next()
    }
  })
}

/* 工具类方法 */
var util = {
  // 判断客户端,0 安卓,1 ios
  'getDevInfo':
    function () {
      var u = navigator.userAgent
      var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
      var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
      if (isAndroid) {
        return 0
      } else if (isiOS) {
        return 1
      }
    }
}
window.util = util

// 应用初始化入口
app.initialize()

// 开发环境
if (window.location.href.indexOf('localhost') > -1) {
  USERNAME = 'chenqy9'
  // 获取权限列表
  getAuthorizeList(function () {
    // 初始化全局变量
    setGlobalEvn()
    // 初始化行业数据源
    window.getDatasource()
    initApp()
  })
}
